package com.github.pig.auth.component.mobile;

import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import com.github.pig.auth.feign.AppUserService;
import com.github.pig.auth.util.LoginType;
import com.github.pig.auth.util.UserDetailsImpl;
import com.github.pig.common.vo.SysRole;
import com.github.pig.common.vo.SysUserRoleVO;
import com.github.pig.common.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.UUID;

/**
 * @author lengleng
 * @date 2018/1/9
 * app登录校验逻辑
 */
public class MobileAuthenticationProvider implements AuthenticationProvider {

    private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
    private AppUserService appuserService;

    @Autowired
    public RedisTemplate redisTemplate;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
        String query = mobileAuthenticationToken.getPrincipal().toString();
        //Object login = redisTemplate.opsForValue().get("_"+query);
        UserDetailsImpl userDetails = null;
        if (!"".equals(query) && query != null){
            String type = query.substring(0,1);
            String id = query.substring(1,query.length());
            if (type.equals(LoginType.wx.getStatus())){ //wx
                UserVO userVO = appuserService.findUserByOpenId(id);
                if (userVO != null){ //已绑定
                    userDetails = buildUserDeatils(userVO);
                }else { //未绑定
                    throw new UsernameNotFoundException ("未绑定用户，请绑定！");

                }
            }else if (type.equals(LoginType.qq.getStatus())){ //qq
                UserVO userVO = appuserService.findUserByQQId(id);
                if (userVO != null){ //已绑定
                    userDetails = buildUserDeatils(userVO);
                }else { //未绑定
                    throw new UsernameNotFoundException("未绑定用户，请绑定！");
                }
            }else if (type.equals(LoginType.mobile.getStatus())){ //手机
                UserVO userVO = appuserService.findUserByMobile(id);
                UserVO newUserVO = new UserVO();
                if (userVO == null) {
                    //throw new UsernameNotFoundException("手机号不存在:" + mobileAuthenticationToken.getPrincipal());
                    newUserVO.setUsername(id);
                    newUserVO.setPassword(ENCODER.encode(UUID.randomUUID().toString().replaceAll("-","")));
                    newUserVO.setPhone(id);
                    appuserService.addAppUser(newUserVO);

                    SysRole sysRole = appuserService.findRoleByRoleCode("visitor"); //游客角色
                    UserVO userVo2 = appuserService.findUserByMobile(id); //再次查询数据

                    SysUserRoleVO sysUserRole = new SysUserRoleVO();
                    sysUserRole.setUserId(userVo2.getUserId());
                    sysUserRole.setRoleId(sysRole.getRoleId());
                    appuserService.addUserRole(sysUserRole);
                    userDetails = buildUserDeatils(userVo2);
                }else {
                    userDetails = buildUserDeatils(userVO);
                }
            }
        }else {
            throw new UsernameNotFoundException("授权异常：qqid或openid为空！");
        }

        MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
        authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
        return authenticationToken;
    }

    private UserDetailsImpl buildUserDeatils(UserVO userVo) {
        return new UserDetailsImpl(userVo);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return MobileAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public AppUserService getUserService() {
        return appuserService;
    }

    public void setUserService(AppUserService userService) {
        this.appuserService = userService;
    }

}
